import { Link } from "../../app_base/module/structure/Link";
import { G_Data } from "../DataCenter";

type CheckInStruct = {
    /**
     * 玩家签到天数
     **/
    checkInDays: number,
    /**
     * 上一次签到的时间（毫秒数）
     */
    lastCheckinTime: number
}

/**
 * 玩家签到数据
 */
export class CheckInLink extends Link<CheckInStruct> {

    constructor() {
        super("checkIn", {
            checkInDays: 0,
            lastCheckinTime: 0
        });
    }

    protected _restSelfData(): void {
        this._data.checkInDays = 0;
        this._data.lastCheckinTime = 0;
    }

    /**
     * 七天累积签到天数
     */
    public get checkInDays(): number {
        return this._data.checkInDays;
    }

    private set checkInDays(value: number) {
        if (value >= 7 && this.canCheckinToday) {
            value = 0;
        }
        let oldValue = this._data.checkInDays;
        this._data.checkInDays = value;
        this.updated("checkInDays", value, oldValue);
    }

    /**今天是否还能签到 */
    public get canCheckinToday(): boolean {
        let lastDay = Math.floor(this._data.lastCheckinTime / (24 * 60 * 60 * 1000));
        let today = Math.floor(G_Data.server.time / (24 * 60 * 60 * 1000));
        return lastDay < today;
    }

    /**玩家签到，签到成功返回true */
    public checkIn(): boolean {
        if (!this.canCheckinToday) return false;
        let oldValue = this._data.lastCheckinTime;
        this._data.lastCheckinTime = G_Data.server.time;
        this.updated("lastCheckinTime", this._data.lastCheckinTime, oldValue);
        this.checkInDays++;
        return true;
    }
    /**这一天是否已经签到 */
    public alreadyCheckinTheDay(dayNum: number): boolean {
        return dayNum <= this.checkInDays;
    }
}